package com.bl.student.service.biz.apply.impl;

import com.bl.student.common.ApiResponseCode;
import com.bl.student.common.CommonServiceException;
import com.bl.student.common.utils.ListUtils;
import com.bl.student.common.utils.UUIDUtils;
import com.bl.student.dao.model.*;
import com.bl.student.dao.redis.model.UserInfo;
import com.bl.student.dao.repository.*;
import com.bl.student.service.biz.apply.ApplyService;
import com.bl.student.service.biz.comment.CommentService;
import com.bl.student.service.biz.teacher.TeacherService;
import com.bl.student.service.biz.user.UserService;
import com.bl.student.service.vo.DelBody;
import com.bl.student.service.vo.DelListBody;
import com.bl.student.service.vo.apply.ApplyAddVo;
import com.bl.student.service.vo.apply.ApplyAgreeVo;
import com.bl.student.service.vo.apply.ApplyVo;
import com.bl.student.service.vo.chat.RoomAddVo;
import com.bl.student.service.vo.teacher.TeacherSimpleInfoVo;
import com.bl.student.service.vo.user.RoomUserInfo;
import com.bl.student.service.vo.user.UserSimpleInfoVo;
import com.google.common.collect.Lists;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import com.bl.student.service.vo.apply.ApplyListVo;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;


import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Log4j2
@Service
public class ApplyServiceImpl implements ApplyService {
    @Autowired
    ApplyRepository applyRepository;

    @Autowired
    UserRepository userRepository;

    @Autowired
    UserService userService;

    @Autowired
    TeacherRepository teacherRepository;
    @Autowired
    TaskRepository taskRepository;

    @Autowired
    RoomRepository roomRepository;

    @Autowired
    CommentService commentService;

    @Autowired
    TeacherService teacherService;

    @Autowired
    ConfirmRepository confirmRepository;

    @Override
    public ApplyListVo getApplyLists(String userid,String taskId,Pageable pageable ){

//        ApplyListVo applyListVo = new ApplyListVo();
//
//        Page <ApplyEntity> applyEntities;
//
//        applyEntities = applyRepository.findByPartybIdOrderByStatusDesc(userid, pageable);
//
//        List <ApplyVo> applyVos = Lists.newArrayList();
//
//        for(ApplyEntity applyEntity : applyEntities) {
//            ApplyVo applyVo = new ApplyVo();
//
//            BeanUtils.copyProperties(applyEntity, applyVo);
//
//            String partyaId = applyEntity.getPartyaId();
//            TeacherEntity teacherEntity = teacherRepository.findOne(partyaId);
//            applyVo.setPartyaNickname(teacherEntity.getNickname());
//            applyVo.setPartyaMobile(teacherEntity.getMobile());
//            applyVo.setPartyaAvatar(teacherEntity.getAvatar());
//
//            UserEntity userEntity = userRepository.findOne(userid);
//            applyVo.setPartybNickname(userEntity.getNickname());
//            applyVo.setPartybMobile(userEntity.getMobile());
//            applyVo.setPartybAvatar(userEntity.getAvatar());
//
//            applyVos.add(applyVo);
//        }

//        applyListVo.setTotalCount(applyEntities.getTotalElements());
//        applyListVo.setList(applyEntities.getContent());

        ApplyListVo applyListVo = new ApplyListVo();

        Page <ApplyEntity> applyEntities;

        applyEntities = applyRepository.findByTaskIdOrderByStatusDesc(taskId, pageable );

        List <ApplyVo> applyVos = Lists.newArrayList();

        for(ApplyEntity applyEntity : applyEntities) {
            ApplyVo applyVo = new ApplyVo();

            BeanUtils.copyProperties(applyEntity, applyVo);

            String partyaId = applyEntity.getPartyaId();
            TeacherEntity teacherEntity = teacherRepository.findOne(partyaId);
            applyVo.setPartyaNickname(teacherEntity.getNickname());
            applyVo.setPartyaMobile(teacherEntity.getMobile());
            applyVo.setPartyaAvatar(teacherEntity.getAvatar());

            String partybId = applyEntity.getPartybId();
            UserEntity userEntity = userRepository.findOne(partybId);
            applyVo.setPartybNickname(userEntity.getNickname());
            applyVo.setPartybMobile(userEntity.getMobile());
            applyVo.setPartybAvatar(userEntity.getAvatar());

            if(userid.equals(partybId)) {
                applyVo.setIsSelf("1");
            } else {
                applyVo.setIsSelf("0");
            }

            applyVos.add(applyVo);
        }

        applyListVo.setTotalCount(applyVos.size());
        applyListVo.setList(applyVos);
        return applyListVo;
    }

    @Override
    public ApplyListVo getTaskApplyLists(String taskId,Pageable pageable, UserInfo userInfo, int status){

        ApplyListVo applyListVo = new ApplyListVo();

        Page <ApplyEntity> applyEntities;

        applyEntities = applyRepository.findByTaskIdAndStatus(taskId, status, pageable);

        List <ApplyVo> applyVos = Lists.newArrayList();

        for(ApplyEntity applyEntity : applyEntities) {
            ApplyVo applyVo = new ApplyVo();

            BeanUtils.copyProperties(applyEntity, applyVo);

            String partyaId = applyEntity.getPartyaId();
            TeacherEntity teacherEntity = teacherRepository.findOne(partyaId);
            applyVo.setPartyaNickname(teacherEntity.getNickname());
            applyVo.setPartyaMobile(teacherEntity.getMobile());
            applyVo.setPartyaAvatar(teacherEntity.getAvatar());
            applyVo.setPartyaHxName(teacherEntity.getHxName());


            String newPartybId = applyEntity.getPartybId();
            UserEntity userEntity = userRepository.findOne(newPartybId);
            if (userEntity != null) {
                applyVo.setPartybNickname(userEntity.getNickname());
                applyVo.setPartybMobile(userEntity.getMobile());
                applyVo.setPartybHxName(userEntity.getHxName());
                applyVo.setPartybInfo(userEntity.getInfo());
                applyVo.setPartybCollege(userEntity.getCollege());
                applyVo.setPartybAvatar(userEntity.getAvatar());
                applyVo.setScore(commentService.getCommentScoreByReceive(newPartybId));
            }

            if (userInfo != null) {
                if(userInfo.getId().equals(newPartybId)) {
                    applyVo.setIsSelf("1");
                } else {
                    applyVo.setIsSelf("0");
                }
            }

            List<ConfirmEntity> confirmEntities = confirmRepository.findByTaskIdAndPartybIdOrderByCreateTimeDesc(taskId, newPartybId);
            if (confirmEntities != null && confirmEntities.size() > 0) {
                applyVo.setConfirmEntity(ListUtils.getFirst(confirmEntities));
            }
            applyVos.add(applyVo);
        }

        applyListVo.setTotalCount(applyEntities.getTotalElements());
        applyListVo.setList(applyVos);

        return applyListVo;
    }



    @Override
    public ApplyListVo getAllApplyLists(String partyaId, String partybId, String taskId,Pageable pageable  ){

        ApplyListVo applyListVo = new ApplyListVo();

        Page <ApplyEntity> applyEntities;
        List <ApplyVo> applyVos = Lists.newArrayList();

        if(partyaId == null && partybId == null && taskId == null ) {
            applyEntities = applyRepository.findAll(pageable );
        } else {
            applyEntities = applyRepository.findMultList(partyaId, partybId,taskId,pageable );
        }

        for(ApplyEntity applyEntity : applyEntities) {
            ApplyVo applyVo = new ApplyVo();
            BeanUtils.copyProperties(applyEntity, applyVo);
            String partyaid = applyEntity.getPartyaId();
            String partybid = applyEntity.getPartybId();
            TeacherEntity teacherEntity = teacherRepository.findOne(partyaid);
            applyVo.setPartyaNickname(teacherEntity.getNickname());
            applyVo.setPartyaMobile(teacherEntity.getMobile());
            applyVo.setPartyaAvatar(teacherEntity.getAvatar());
            UserEntity userEntity = userRepository.findOne(partybid);
            applyVo.setPartybNickname(userEntity.getNickname());
            applyVo.setPartybMobile(userEntity.getMobile());
            applyVo.setPartybAvatar(userEntity.getAvatar());
            applyVos.add(applyVo);
        }
        applyListVo.setTotalCount(applyVos.size());
        applyListVo.setList(applyVos);
        return applyListVo;

//        applyListVo.setTotalCount(applyEntities.getTotalElements());
//        applyListVo.setList(applyEntities.getContent());

    }


    @Override
    public void del(DelBody id) {
        applyRepository.delete(id.getId());
    }

    @Override
    public void delList(DelListBody idList) {
        for(String id : idList.getList()) {
            applyRepository.delete(id);
        }
    }

    @Override
    public void apply(ApplyAddVo applyAddVo, String partybid) {

        UserEntity userEntity = userRepository.findOne(partybid);

        if (!userEntity.getAuth().equals("1")) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "用户未授权无法接单");
        }

        ApplyEntity applyEntity1 = applyRepository.findByTaskIdAndPartybId(applyAddVo.getTaskId(), partybid);
        if (applyEntity1 != null) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "不能重复申请");
        }

        TeacherEntity teacherEntity = teacherRepository.findOne(applyAddVo.getPartyaId());

        if (teacherEntity.getOpenId().equals(userEntity.getOpenId())) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "不能接自己发布的任务");
        }

        // 乙方金额变动
//        userEntity.setMoney(userEntity.getMoney().subtract(applyAddVo.getMoney()));
//        userEntity.setUpdateTime(new Date());
//        userRepository.save(userEntity);

        ApplyEntity applyEntity = new ApplyEntity();
        BeanUtils.copyProperties(applyAddVo, applyEntity);
        applyEntity.setCreateTime(new Date());
        applyEntity.setUpdateTime(new Date());
        applyEntity.setPartyaId(applyAddVo.getPartyaId());
        applyEntity.setTaskId(applyAddVo.getTaskId());
        applyEntity.setPartybId(partybid);
        applyEntity.setApplyId(UUIDUtils.getUUID());
        applyEntity.setMoney(applyAddVo.getMoney());
        applyEntity.setUrl(applyAddVo.getUrl());
        applyEntity.setComment(applyAddVo.getComment());
//        状态：0-已申请，1-已接受 2- 已拒绝
        applyEntity.setStatus(0);
        applyRepository.save(applyEntity);
    }

    @Override
    public void agree(ApplyAgreeVo applyAgreeVo) {

        String taskid = applyAgreeVo.getTaskId();
        TaskEntity taskEntity1 = taskRepository.findOne(taskid);
        int partybCount = taskEntity1.getPartybCount();
        String applyid = applyAgreeVo.getApplyId();

        List <ApplyEntity> applyEntitiesHasAgree = applyRepository.findByTaskIdAndStatus(taskid, 1);

        if (applyEntitiesHasAgree.size() > partybCount) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "已经达到人数上限~");
        }

        List <ApplyEntity> applyEntities = applyRepository.findByTaskId(taskid);
        for(ApplyEntity applyEntity : applyEntities) {
            String apply_id = applyEntity.getApplyId();
            String partyb_id = applyEntity.getPartybId();
            if(applyid.equals(apply_id)) {
//                选择该乙方，建立关联，修改为接收状态
                applyEntity.setStatus(1);
                applyEntity.setStartTime(new Date());
//                修改task表为online状态
                TaskEntity taskEntity = taskRepository.findOne(taskid);
                // 人数达到后，状态改变
                if ((applyEntitiesHasAgree.size() + 1) == partybCount) {
                    taskEntity.setStatus("ONLINE");
                }
                taskEntity.setUpdateTime(new Date());
//                taskEntity.setPartybId(partyb_id);
                taskRepository.save(taskEntity);
            }
            applyRepository.save(applyEntity);
        }
    }

    @Override
    public void forceOnline(DelBody taskId) {
        log.info("forceOnline taskId ===== ", taskId);
        TaskEntity taskEntity = taskRepository.findOne(taskId.getId());
        if (!taskEntity.getClassb().equals("群招")) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "不是群招任务，无法点击开始");
        }

        List <ApplyEntity> applyEntities = applyRepository.findByTaskIdAndStatus(taskId.getId(), 1);

        if (applyEntities == null || applyEntities.size() == 0) {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "没有已选择用户，无法点击开始");
        }

        for (ApplyEntity applyEntity : applyEntities) {
            applyEntity.setStartTime(new Date());
            applyRepository.save(applyEntity);
        }

        taskEntity.setStatus("ONLINE");
        taskEntity.setAdNeedNum(applyEntities.size() + "");
        taskEntity.setPartybCount(applyEntities.size());
        taskEntity.setUpdateTime(new Date());
        taskRepository.save(taskEntity);
    }


    @Override
    public List<ApplyEntity> getApplyListsByPartybAndStatus(String partbId, int status) {

        List <ApplyEntity> applyEntities;

        applyEntities = applyRepository.findByPartybIdAndStatusOrderByStatusDesc(partbId, status);
        return applyEntities;
    }

    @Override
    public void addRoom(RoomAddVo roomAddVo) {
        RoomEntity roomEntity = new RoomEntity();
        BeanUtils.copyProperties(roomAddVo, roomEntity);
        roomEntity.setCreateTime(new Date());
        roomEntity.setUpdateTime(new Date());
        roomRepository.save(roomEntity);
    }

    @Override
    public String getRoom(String partyaHxName, String partybHxName, String taskId) {
        List<RoomEntity> roomEntities = roomRepository.findByPartyaHxNameAndPartybHxNameAndTaskId(partyaHxName, partybHxName, taskId);
        if (roomEntities == null || roomEntities.size() == 0) {
            return null;
        } else {
            return ListUtils.getFirst(roomEntities).getRoomId();
        }
    }

    @Override
    public RoomUserInfo getUserInfoByRoom(String roomId) {
        RoomUserInfo roomUserInfo = new RoomUserInfo();
        log.info("roomId ==== ", roomId);
        RoomEntity roomEntity = roomRepository.findOne(roomId);
        UserEntity userEntity = userService.getUserByHxName(roomEntity.getPartybHxName());
        TeacherEntity teacherEntity = teacherService.getTeacherByHxName(roomEntity.getPartyaHxName());
        log.info("getPartybHxName ====", roomEntity.getPartybHxName());
        UserSimpleInfoVo userSimpleInfoVo = new UserSimpleInfoVo();
        BeanUtils.copyProperties(userEntity, userSimpleInfoVo);

        TeacherSimpleInfoVo teacherSimpleInfoVo = new TeacherSimpleInfoVo();
        log.info("getPartyaHxName =====", roomEntity.getPartyaHxName());
        BeanUtils.copyProperties(teacherEntity, teacherSimpleInfoVo);

        roomUserInfo.setPartyaInfo(teacherSimpleInfoVo);
        roomUserInfo.setPartybInfo(userSimpleInfoVo);

        TaskEntity taskEntity = taskRepository.findOne(roomEntity.getTaskId());

        roomUserInfo.setStatus(taskEntity.getStatus());

        return roomUserInfo;

    }

    /**
     * 已通过列表
     * @param taskId
     * @return
     */
    @Override
    public List<UserSimpleInfoVo> getApplyListAgree(String taskId) {
        List<UserSimpleInfoVo> userSimpleInfoVoList = new ArrayList<>();
        List<ApplyEntity> applyListVoList = applyRepository.findByTaskIdAndStatus(taskId, 1);
        for (ApplyEntity applyEntity : applyListVoList) {
            UserSimpleInfoVo partybSimpleInfoVo = userService.getUserById(applyEntity.getPartybId(), "PARTYB");
            userSimpleInfoVoList.add(partybSimpleInfoVo);
        }
        return userSimpleInfoVoList;
    }

    @Override
    public void modifyMoney(String applyId, BigDecimal money){
        ApplyEntity applyEntity = new ApplyEntity();
        applyEntity = applyRepository.findOne(applyId);
        String taskId = applyEntity.getTaskId();
        TaskEntity taskEntity = taskRepository.findOne(taskId);
        if("PRE".equals(taskEntity.getStatus()) ) {
            applyEntity.setMoney(money);
            applyEntity.setUpdateTime(new Date());
            applyRepository.save(applyEntity);
        } else {
            throw new CommonServiceException(ApiResponseCode.DATA_INCORRECT.getCode(), "该任务状态下，不可修改");
        }
    }
}
